/* 
 * File:   resource.c
 * Author: bjorn
 *
 * Created on September 3, 2007, 8:13 PM
 */

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "object.h"
#include "memory.h"
#include "script.h"
#include "rope.h"
#include "image.h"
#include "screen.h"
#include "resource.h"
/*
 * 
 */



Resource::~Resource() {
	
}

int file_exists_list(Ropelist list) {
	Ropelist::size_type stop = list.size();
  	Ropelist::size_type index = 0;
  	for (index = 0; index < stop; index++) {
    	Rope path = list[index];
		printf("Scanning %s\n", path.c_str());
    	if( file_exists( path.c_str() ) ) {
			return index;
		}
  	}
	return -1;
}

bool Resource::scan() {
	_directories = _path.split(ERUTA_PATH_SEP_STR);
	int aid = file_exists_list(_directories);
	if( aid < 0 ) {
		return false;
	}
	_config = _directories[aid];
	_script.setstring("ERUTA_CONFIG", _config.c_str());	
	return run_script(_config);
	return true;
}

bool Resource::run_script(const Rope filename) {
	int errlevel = _script.run(filename.c_str());
	if(errlevel) return false;
	return true;
} 

Resource::Resource() {
	char * homestr	= getenv("ERUTA_HOME");
	_path			= Rope(ERUTA_RESOURCE_PATH);	
	
	if(homestr) {
		_path.append(ERUTA_PATH_SEP_STR);
		_path.append(homestr);
	}
}	


Image Resource::loadimage_c(const char * imagename) {
	Rope fname(_script.getstring("ERUTA_IMAGE_DIR", "./share/image/"));
	Image result;	
    fname.append(imagename);
	result = image_load_c(fname.c_str());
	return result;
}

Image Resource::loadimage_display_c(const char * imagename) {
	Image aid = loadimage_c(imagename);
	Image result =  SDL_DisplayFormat(aid);
	image_free(aid);
	return result;
} 

Fontpointer Resource::loadfont_c(const char * imagename, int size) {
	Rope fname(_script.getstring("ERUTA_FONT_DIR", "./share/font/"));
	Fontpointer result;	
	fname.append(imagename);
	printf("Loading font %s ...\n", fname.c_str());
	result = Font::load(fname.c_str(), size);
	if(result) printf("font loaded OK\n");
	return result;
}


bool file_exists(const char *filename) {
    FILE * file;
    file = fopen(filename, "r");
    if(!file) return false;
    fclose(file);
    return true;
}

char * resource_filename(const char * name) {
     return NULL;
} 


FILE * resource_file_open(char * name) {
    return NULL;
}

